//
//  APWorksDetailViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/10.
//

#import "APWorksDetailViewController.h"
#import "APWorksDetailNaviBar.h"
#import "APAPWorksDetailCommentTextCell.h"
#import "APWorksDetailCommentVoiceCell.h"
#import "APWorksDetailHeaderView.h"
#import "APChatInputView.h"
#import "APVoiceReocrderManager.h"
#import "APDiscoveryDataManager.h"
#import "APTranslateManager.h"
#import "APBottomMenuViewController.h"
#import "APUserPageViewController.h"
#import "APLoginManager.h"
@interface APWorksDetailViewController ()<UITableViewDelegate,UITableViewDataSource,ChatInputViewDelegate>
@property (nonatomic, strong) APWorksDetailNaviBar *naviBarView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) APWorksDetailHeaderView *headerView;
@property (nonatomic, strong) APChatInputView *commentInputView;
@property (nonatomic, strong) NSMutableArray *comments;
@property (nonatomic, assign) NSInteger voicePlayingSection;
@end

@implementation APWorksDetailViewController

- (NSMutableArray *)comments{
    if (!_comments) {
        _comments = [NSMutableArray array];
    }
    return _comments;
}

- (APChatInputView *)commentInputView{
    if (!_commentInputView) {
        _commentInputView = [[APChatInputView alloc] init];
        _commentInputView.naviView = self.navigationController.view;
        _commentInputView.delegate = self;
    }
    return _commentInputView;
}

- (APWorksDetailNaviBar *)naviBarView{
    if (!_naviBarView) {
        _naviBarView = [[APWorksDetailNaviBar alloc] init];
        [_naviBarView.backButton addTarget:self action:@selector(worksDetailBackButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
        [_naviBarView.moreButton addTarget:self action:@selector(moreButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_naviBarView.avatarControl addTarget:self action:@selector(avatarButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _naviBarView;
}

- (APWorksDetailHeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[APWorksDetailHeaderView alloc] init];
        [_headerView.upvoteButton addTarget:self action:@selector(worksUpvoteButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView.translateControl addTarget:self action:@selector(translateButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _headerView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = UIColor.clearColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorColor = UIColor.clearColor;
        _tableView.automaticallyAdjustsScrollIndicatorInsets = false;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tableView.tableHeaderView = self.headerView;
        [_tableView registerClass:[APWorksDetailCommentVoiceCell class] forCellReuseIdentifier:@"voice"];
        [_tableView registerClass:[APAPWorksDetailCommentTextCell class] forCellReuseIdentifier:@"text"];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _voicePlayingSection = -1;
    [self initUI];
    [self refreshData];
    [self refreshComments];
    [self doTranslate:false];

}

- (void)refreshComments{
    if (self.comments.count > 0) {
        [self.tableView reloadData];
        return;
    }
   NSArray *result = [[APDiscoveryDataManager shareInstance] loadCommentsByWorksId:_worksModel.worksId];
    if (result && result.count > 0) {
        [self.comments addObjectsFromArray:result];
    }
    [self.tableView reloadData];
}

- (void)refreshData{
//    APBroadcasterModel *userModel = [[APUserDataManager shareInstance] searchUserByUserId:_worksModel.userId];
    if (_worksModel.isCreate) {
       UIImage *image =  [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",images_path,_worksModel.avatar]];
        self.naviBarView.avatarControl.avatarImageView.image = image;
    }else{
        [self.naviBarView.avatarControl.avatarImageView sd_setImageWithURL:[NSURL URLWithString:_worksModel.avatar]];
    }
    _naviBarView.nameLabel.text = _worksModel.nickname;
    _naviBarView.avatarControl.followButton.hidden = true;
    NSString *ballImage = [BaseDataManager ballImageName:_worksModel.ballType];
    _naviBarView.ballImageView.image = [UIImage imageNamed:ballImage];
    _headerView.imagesView.isLocalFile = _worksModel.isCreate;
    _headerView.imagesView.urlArray = _worksModel.images;
    _headerView.titleLabel.text = _worksModel.title;
    _headerView.contentLabel.text = _worksModel.content;
    _headerView.upvoteButton.selected =  _worksModel.upvote;
    _headerView.translateContentLabel.text = _worksModel.translateContent;
    BOOL isSelf = [[[APLoginManager shareInstance] userInfo].userId isEqualToString:_worksModel.userId];
    _naviBarView.moreButton.hidden = isSelf;
    
    CGSize contentSize = [_worksModel.content sizeWithFont:[LYFont fontWithSize:12 fontName:LYFontNamepfr] maxSize:CGSizeMake(ScreenWidth - 40, CGFLOAT_MAX)];
    CGFloat translateH = 0;
    if (_worksModel.translateContent){
        translateH = [_worksModel.content sizeWithFont:[LYFont fontWithSize:12 fontName:LYFontNamepfr] maxSize:CGSizeMake(ScreenWidth - 40, CGFLOAT_MAX)].height + 16;
    }
    self.headerView.frame = CGRectMake(0, 0, ScreenWidth, 421 + contentSize.height + translateH);
    self.tableView.tableHeaderView = self.headerView;
    
}

- (void)chatInputView:(APChatInputView *)inputView sendMessage:(NSString *)message{
    [self.view ShowProgress];
    if ([message isEqualToString:@""]) {
        [self.view ShowProgressOnlyLabel:@"comment content is empty"];
        return;
    }
    APUserModel *userInfo = [[APLoginManager shareInstance] userInfo];

    APCommentModel *model = [[APCommentModel alloc] init];
    model.userId = userInfo.userId;
    model.nickname = userInfo.nickname;
    model.avatar = userInfo.avatarUrl;
    model.isUpvote = false;
    model.content = message;
    model.type = 0;
    [self.comments insertObject:model atIndex:0];
    [[APDiscoveryDataManager shareInstance] saveCommentsWorksId:_worksModel.worksId comments:self.comments];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self.view removeProgress];
    });
}
- (void)chatInputView:(APChatInputView *)inputView sendMediaType:(chatMessageType)type filePath:(NSString *)filePath{
    NSString *fileName = [[APVoiceReocrderManager shareVoiceReocrder] getCurrentFileName];
    [self.view ShowProgress];
    APUserModel *userInfo = [[APLoginManager shareInstance] userInfo];
    APCommentModel *model = [[APCommentModel alloc] init];
    model.userId = userInfo.userId;
    model.nickname = userInfo.nickname;
    model.avatar = userInfo.avatarUrl;

    model.isUpvote = false;
    model.content = fileName;
    model.type = 1;
    model.seconds = (int)inputView.voiceButton.seconds;
    [self.comments insertObject:model atIndex:0];
    [[APDiscoveryDataManager shareInstance] saveCommentsWorksId:_worksModel.worksId comments:self.comments];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [self.view removeProgress];
    });

}

- (void)worksDetailBackButtonDidClick{
    [self.navigationController popViewControllerAnimated:true];
}

- (void)voicePlayerDidClicK:(UIControl *)sender{
    APWorksDetailCommentVoiceCell *_voicePlayingCell;
    if (_voicePlayingSection != -1) {
        _voicePlayingCell  = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_voicePlayingSection]];
        _voicePlayingCell.voiceIconImageView.hidden = false;
        _voicePlayingCell.svgaImageView.hidden = true;
        [_voicePlayingCell.svgaImageView stopAnimation];
    }
    CGPoint point = sender.center;
    point = [self.tableView convertPoint:point fromView:sender.superview];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
    APCommentModel *model = self.comments[indexPath.section];
    APWorksDetailCommentVoiceCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (_voicePlayingSection == indexPath.section) {
       _voicePlayingSection = -1;
        [[APVoiceReocrderManager shareVoiceReocrder] stopPlay];
        _voicePlayingCell.voiceIconImageView.hidden = false;
        _voicePlayingCell.svgaImageView.hidden = true;
        return;
    }
    _voicePlayingSection = indexPath.section;
    [cell.svgaImageView startAnimation];
    cell.voiceIconImageView.hidden = true;
    cell.svgaImageView.hidden = false;
    NSString *file = [NSString stringWithFormat:@"%@/%@",VOICE_RECORDFILE_FOLDER_PATH,model.content];
    WS(ws);
    [[APVoiceReocrderManager shareVoiceReocrder] playWithFile:file finish:^(BOOL res) {
        [cell.svgaImageView stopAnimation];
        cell.voiceIconImageView.hidden = false;
        cell.svgaImageView.hidden = true;
        ws.voicePlayingSection = -1;
    }];
}


- (void)upvoteButtonDidClicK:(UIControl *)sender{
    CGPoint point = sender.center;
    point = [self.tableView convertPoint:point fromView:sender.superview];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point];
    APCommentModel *model = self.comments[indexPath.section];
    model.isUpvote = !model.isUpvote;
    [self.tableView reloadData];
    [[APDiscoveryDataManager shareInstance] saveCommentsWorksId:_worksModel.worksId comments:self.comments];
}

- (void)worksUpvoteButtonDidClick:(UIButton *)sender{
    _worksModel.upvote = !_worksModel.upvote;
    [[APDiscoveryDataManager shareInstance] updateWorks:_worksModel.worksId];
    _headerView.upvoteButton.selected =  _worksModel.upvote;
    
}

- (void)translateButtonDidClick:(APTranslateControl *)sender{
    [self doTranslate:YES];
}

- (void)doTranslate:(BOOL)showProgress{
    if (!_worksModel.translateContent) {
        NSString *lan = [NSLocale currentLocale].languageCode;
        if (showProgress) {
            [self.view ShowProgress];
        }
        WS(ws);
        [[APTranslateManager shareInstance] translateText:_worksModel.content toLan:lan result:^(NSString * _Nonnull translateContent) {
            if (showProgress) {
                [ws.view removeProgress];
            }
            ws.worksModel.translateContent = translateContent;
            [ws refreshData];
        }];
    }
}

- (void)moreButtonDidClick:(UIButton *)sender{
    APBottomMenuViewController *menuVC = [[APBottomMenuViewController alloc] init];
    [menuVC setCallBack:^(NSInteger index) {
        if (index == 1) {
            [self.navigationController popViewControllerAnimated:true];
        }else{
            [self refreshData];
        }
    }];
    menuVC.userId = _worksModel.userId;
    [self.tabBarController presentViewController:menuVC animated:true completion:nil];
    
}

- (void)avatarButtonDidClick:(APAvatarControl *)sender{
    APUserPageViewController *userVC = [[APUserPageViewController alloc] init];
    userVC.userId = _worksModel.userId;
    [self.navigationController pushViewController:userVC animated:true];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.comments.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 16;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    APCommentModel *model = self.comments[indexPath.section];
    if (model.type == 1) {
        APWorksDetailCommentVoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"voice"];
        [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
        cell.nameLabel.text = model.nickname;
        cell.upvoteButton.selected = model.isUpvote;
        cell.commentModel = model;
        cell.timeLabel.text = [NSString stringWithFormat:@"%zdS",model.seconds];
        [cell.upvoteButton addTarget:self action:@selector(upvoteButtonDidClicK:) forControlEvents:UIControlEventTouchUpInside];
        [cell.voiceControl addTarget:self action:@selector(voicePlayerDidClicK:) forControlEvents:UIControlEventTouchUpInside];
        if (_voicePlayingSection == indexPath.section) {
            cell.voiceIconImageView.hidden = true;
            cell.svgaImageView.hidden = false;
        }else{
            cell.voiceIconImageView.hidden = false;
            cell.svgaImageView.hidden = true;
        }

        return cell;
    }else{
        APAPWorksDetailCommentTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"text"];
        [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:model.avatar]];
        cell.nameLabel.text = model.nickname;
        cell.contentLabel.text = model.content;
        cell.upvoteButton.selected = model.isUpvote;
        [cell.upvoteButton addTarget:self action:@selector(upvoteButtonDidClicK:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}



- (void)initUI{
    [self.view addSubview:self.commentInputView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.naviBarView];
    [self.naviBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
    }];
    [self.commentInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(68);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.commentInputView.mas_top);
    }];
    
}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
    }];
}


@end
